/*
 *@# AppletLink Created on 2004-8-27
 *
 *
 * Copyright: Bluejay Networks Inc. & Inquiry Management Systems Ltd.  2004
 *
 * This software is the proprietary information of Bluejay Networks Inc. & 
 * Inquiry Management Systems Ltd.  
 * Use is subject to license terms.
 */
package com.ims.iaa.AD;

import com.ims.iaa.IaaDebug; 
import com.ims.iaa.IaaUtil;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Timestamp;
import java.util.List;

/**
 * This class represents applet link data collected by spiders. 
 * @author ShengMeng Bai
 *
 * @version 1.00, 27 AUG. 2004
 */
public class AppletLink extends AdDataLink {
	
	private int m_iSrcReqStatus = CONN_NEVER;
	
	//the web page URL which contain the applet
	private URL m_ContainerUrl;
	//the class URL or jar URL
	private URL m_SrcUrl;
	//the User Agent string used during the search process
	private String m_sUserAgent;
	//cookie to save the jar or java class
	private transient SimpleCookies m_Cookie;
	//the applet object, contain data, size
	private AdApplet m_applet = new AdApplet();
	//the host URL which contain the applet, which set at connectToResource()
	private String m_sAppletSite;
	// the time of connecting to the applet.
	private Timestamp m_objCollectTime;
	/**
	 * @see #getAppletParamStr
	 */
	private String m_sAppletParam;

	/**
	 * The constructor construct new Applet Link, 
	 * 
	 * @param srcURL 				the Applet URL.
	 * @param ContainerUrl			the web page URL which contain the Applet
	 * 
	 * @return void
	 */
	public AppletLink( URL srcURL, URL ContainerUrl ){
		m_SrcUrl = srcURL;
		m_ContainerUrl = ContainerUrl;
		//Applet usually is advertisement.
		incPossibility(100);
	}
	/**
	 * The constructor construct updated Applet impression, 
	 * @param sSrc, Applet URL
	 * @param iImpID, the impression ID which saved in database
	 * @param iImageID, the image ID which saved in database
	 * @param sUserAgent
	 * 
	 * @see com.ims.iaa.SpiderDBConnectionImpl#getReConnectImp(int)
	 */
	public AppletLink(URL urlSRC, int iImpID, int iImageID, String sUserAgent){
		m_SrcUrl = urlSRC;
		setOldImpressionID(iImpID);
		setOldImageID(iImageID);
		setUserAgent(sUserAgent);
	}
	/**
	 * Get the advertisement type, it is "APPLET" or "APPLET/POPUP". 
	 * @return
	 */
	public String getAdType()  {
		if(isPopupData()){
			return ADTYPE_POPUP_APPLET;
		}else{
			return ADTYPE_APPLET;
		}
	}
	/**
	 * get AdApplet object.
	 */
	public AdData getAdData(){
		return m_applet;
	}
	/**
	 * Set the Applet height, it should get from
	 * the web page which container the Applet.
	 * 
	 * @param iHeight Applet height in pixels
	 * 
	 * @return void
	 */
	public void setHeight( int iHeight ){
		m_applet.setHeight( iHeight );
	}
	/**
	 * Get the Applet height
	 * @return Applet height in pixels
	 */
	public int getHeight(){
		return m_applet.getHeight();
	}
	
	/**
	 * set the Applet width, it should get from
	 * the web page which container the Applet
	 * 
	 * @param iWidth Applet width in pixels
	 * 
	 * @return void
	 */
	public void setWidth( int iWidth ){
		m_applet.setWidth( iWidth );
	}
	/**
	 * Get the Applet width
	 * @return Applet width in pixels
	 */
	public int getWidth(){
		return m_applet.getWidth();
	}
	/**
	 * Set the User Agent string which used during the search process
	 * @param agent
	 */
	public void setUserAgent(String sAgent)  {
		m_sUserAgent = sAgent;
	}
	/**
	 * Get the source URL of the har file.
	 * @return 
	 */
	public URL getSrcURL(){
		return m_SrcUrl;
	}
	/**
	 * Get the source URL string of the java file.
	 * @return 
	 */
	public String getSrcURLStr(){
		if(m_SrcUrl != null){
			return m_SrcUrl.toExternalForm();
		}else{
			return null;
		}
	}
	
	/**
	 * Get the host URL of the jar file source.
	 * @return
	 */
	public String getAdDataSite(){
		return m_sAppletSite;
	}
	/**
	 * Get the web URL which this applet is showed.
	 * @return
	 */
	public URL getContainerURL(){
		return m_ContainerUrl;
	}
	//we cann't get the target url from web, return null;
	public String getRealTargetURLStr() {
		return null;
//		return m_sRealTargetUrlStr;
	}
	//we cann't get the target url from web, return null;
	public URL getTargetURL(){
		return null;
//		return m_objTargetURL;
	}
	//we cann't get the target url from web, return null;
	public String getTargetURLStr(){
		return null;
	}
	/**
	 * Because applet tag contain some param, this param used by applet,
	 * so we must save it for show, usual a applet tag like this:
	 * <applet code="..." archive="..." codebase="..." width=... height=...>
	 * <param name="..." value="...">
	 * <param name="..." value="...">
	 * </applet>
	 * 
	 * when we save it we will save it like this:
	 * <applet code="..." archive="ReplaceJar" width=... height=...>
	 * <param name="..." value="...">
	 * <param name="..." value="...">
	 * </applet>
	 * 
	 * so when we show it, we will replace "ReplaceJar" with real jar url.
	 * 
	 * @return m_sAppletParam
	 */
	public String getAppletParamStr(){
		return m_sAppletParam;
	}
	public void setAppletParamStr(String sParam){
		m_sAppletParam = sParam;
	}
	
	/**
	 * The host URL advertiser, usualy, this infomation will be got through
	 * click the applet when applet is playing, but we cann't get it from web,
	 * so it may be null.
	 * 
	 * @return null
	 * @author ShengMeng Bai at 2004-08-27
	 */
	public String getAdvertiser(){
		return null;
	}
		
	public Timestamp getCollectTime() {
		// collectTime was set in the connectToRecources()  method;
		return m_objCollectTime;
	}
	/**
	 * Get the state of linked to jar file, 
	 * it may be CONN_NEVER, CONN_SUCCESS, CONN_BAD_URL, CONN_FAILURE
	 * 
	 * @return
	 */
	public int getSrcReqStatus(){
		return m_iSrcReqStatus;
	}
	/**
	 * Connect the java file to get some parammeter
	 */
	private void connectToResource() {
		// try to get the jar file content.
		if(m_SrcUrl == null){
			IaaUtil.log("There isn't jar file in this Applet, don't connect to resource.");
			return;
		}
		URLConnection uc = null;
		m_Cookie = new SimpleCookies();
		try  {
			uc = m_SrcUrl.openConnection();
			uc.setRequestProperty("User-Agent", m_sUserAgent);
			IaaDebug.begin("connect java file " + uc.getURL());
			uc.connect();
			IaaDebug.end("connect java file " + uc.getURL());
			m_Cookie.readCookies( uc );

			m_applet.setDataSize( uc.getContentLength() );
			m_applet.setDataType( uc.getContentType() );
			m_sAppletSite = uc.getURL().getHost();
			
			m_iSrcReqStatus = CONN_SUCCESS;
			
		} catch( Exception e ){
			m_iSrcReqStatus = CONN_FAILURE;
			if( IaaDebug.Debug ) {
				IaaUtil.log("!!!!Error make connection to the jar file " + e);
			}
		}

		m_objCollectTime = new Timestamp(  System.currentTimeMillis() );
		if ( AdApplet.SAVEAPPLET && (m_applet.getDataSize() < AdApplet.MAXFILESIZE )) {
			if(IaaDebug.AuxDebug)IaaDebug.begin("connect to the java file ");		
			try  {
				IaaDebug.begin("getInputStream for jar file " + uc.getURL());
				BufferedInputStream bs = new BufferedInputStream(uc.getInputStream());
				IaaDebug.end("getInputStream " + uc.getURL());
	
				byte[] buf = new byte[1024];
				int readNum =0;

				ByteArrayOutputStream picOutStream = new ByteArrayOutputStream();

				IaaDebug.begin("read jar file inputStream " + uc.getURL());
				while ( (readNum = bs.read(buf)) != -1)  {
						picOutStream.write(buf,0,readNum);
				}
				bs.close();
				IaaDebug.end("read jar file inputStream " + uc.getURL());

				m_applet.setData(picOutStream.toByteArray());
				IaaDebug.end("set jar file data");

				picOutStream.close();
				if(IaaDebug.AuxDebug)IaaDebug.end("connect to the jar file ");		
			} catch ( Exception e ) {
				m_iSrcReqStatus = CONN_FAILURE;
				IaaUtil.log( "!!!!Get jar file form the connection input stream error " + e );
			}
		} else {
			if(IaaDebug.Debug) IaaUtil.log("jar file data too big to save");	
			//Note: either java file is too big or we do not want to save the jar file, 
			// then the AppletData is still null
		}
	}
	/* (non-Javadoc)
	 * @see com.ims.iaa.AD.AdDataLink#parse(java.util.List)
	 */
	public boolean parse(List lstAgency,List lstAdSize) {
		connectToResource();
		return true;
	}
	/* (non-Javadoc)
	 * @see com.ims.iaa.AD.AdDataLink#isConnectSuccessful()
	 */
	public boolean isConnectSuccessful() {
		if(m_iSrcReqStatus == CONN_SUCCESS){
			return true;
		}else{
			return false;
		}
	}
	
	public String toString(){
	    return "APPLET: " + m_SrcUrl.toString();
	}
}
